package com.uplift.mobile.realty.service.impl;

import com.github.pagehelper.PageHelper;
import com.uplift.common.Const;
import com.uplift.common.base.ServiceReslut;
import com.uplift.mobile.realty.dao.RealtyFileMapper;
import com.uplift.mobile.realty.model.RealtyFileModel;
import com.uplift.mobile.realty.service.IRealtyFileService;
import com.uplift.mobile.sys.model.DictModel;
import com.uplift.mobile.sys.service.IDictService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.util.*;

@Service
@Transactional
public class RealtyFileServiceImpl implements IRealtyFileService {

	@Autowired
	private RealtyFileMapper realtyFileMapper;

	@Autowired
	private IDictService iDictService;

	@Override
	public List<Map<String, Object>> queryRealtyFile(RealtyFileModel realtyFileModel) {
		PageHelper.startPage(realtyFileModel.getPage(), realtyFileModel.getLimit());

		return this.realtyFileMapper.selectRealtyFile(realtyFileModel);
	}

	@Override
	public ServiceReslut addRealtyFile(RealtyFileModel realtyFileModel) throws Exception {
		if(realtyFileModel.getFiles() != null) {

			String[] fileTypes = StringUtils.split(realtyFileModel.getFileTypes(),",");
			if(fileTypes.length != realtyFileModel.getFiles().length) {
				return ServiceReslut.newServiceReslut(0, "附件与附件类型不匹配。");
			}
			CommonsMultipartFile cmf = null;
			String fileType = null;
			for (int i = 0; i < realtyFileModel.getFiles().length; i++) {
				cmf = realtyFileModel.getFiles()[i];
				fileType = fileTypes[i];

				FileItem item = cmf.getFileItem();
				String fileName = item.getName();
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
				String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
				String newFilePath = "product/" + newFileName;
				File file = new File(Const.DIR_UPLOAD_BASE + newFilePath);
				item.write(file);
				// 设置图片路径
				realtyFileModel.setFilePath(newFilePath);
				realtyFileModel.setFileName(fileName);
				realtyFileModel.setBusiType(fileType);
				realtyFileModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				realtyFileModel.setCreateTime(new Date());
				realtyFileModel.setState("1");

				realtyFileMapper.insertRealtyFile(realtyFileModel);
			}

			return ServiceReslut.newServiceReslut(1, "");
		}

		return ServiceReslut.newServiceReslut(0, "没有添加任何附件");
	}

	@Override
	public ServiceReslut updateRealtyFile(RealtyFileModel realtyFileModel) throws Exception {
		//删除附件
		deleteFiles(realtyFileModel);
		//添加附件
		return addRealtyFile(realtyFileModel);
	}

	private void deleteFiles(RealtyFileModel realtyFileModel) {
		if(realtyFileModel==null || StringUtils.isBlank(realtyFileModel.getDelFiles())){
			return;
		}

		String[] delFiles = StringUtils.split(realtyFileModel.getDelFiles(),",");
		RealtyFileModel _realtyFileModel = null;
		for (String delFile : delFiles) {
			_realtyFileModel = new RealtyFileModel();
			_realtyFileModel.setId(delFile);
			deleteRealtyFile(_realtyFileModel);
		}
	}

	@Override
	public ServiceReslut deleteRealtyFile(RealtyFileModel realtyFileModel) {
		realtyFileModel.setState("0");		//删除状态
		realtyFileModel.setUpdateTime(new Date());
		return ServiceReslut.newServiceReslut(realtyFileMapper.updateRealtyFile(realtyFileModel), "");
	}

	@Override
	public List<Map<String, Object>> queryRealtyTypeFile(RealtyFileModel realtyFileModel) {
//		if(StringUtils.isBlank(realtyFileModel.getRoomId())) {
//			return null;
//		}

		//获取附件类型
		List<Map<String, Object>> types = getFileTypes();
		if(types==null || types.size()==0) {
			return null;
		}

		List<Map<String, Object>> allTypeFile = new ArrayList<>();

		List<Map<String, Object>> typeFiles;
		Map<String, Object> typeFile = null;
		String fileType ;
		for (Map<String, Object> type : types) {
			typeFile = new HashMap<>();
			if(type.get("typeCode") == null) {
				continue;
			}

			fileType = type.get("typeCode").toString();
			realtyFileModel.setBusiType(fileType);
			if(StringUtils.isNoneBlank(realtyFileModel.getMessageId())) {
				typeFiles = this.realtyFileMapper.selectMessageRealtyFile(realtyFileModel);
			} else {
				typeFiles = this.realtyFileMapper.selectRealtyFile(realtyFileModel);
			}

			typeFile.put("typeCode", fileType);
			typeFile.put("typeName", type.get("typeValue"));
			hanldTypeFiles(typeFiles, typeFile);		//添加filehosturl

			allTypeFile.add(typeFile);
		}

		return allTypeFile;
	}

	/**
	 * 获取附件类型
	 * @return
	 */
	private List<Map<String, Object>> getFileTypes() {
		List<Map<String, Object>> types = new ArrayList<>();

		DictModel dictModel = new DictModel();
		dictModel.setType("fileType");
		List<Map<String, Object>> maps = iDictService.queryDict(dictModel);
		if(maps==null || maps.size()==0) {
			return null;
		}

		Map<String, Object> type = null;
		for (Map<String, Object> map : maps) {
			type = new HashMap<>();
			type.put("typeCode", map.get("code"));
			type.put("typeValue", map.get("value"));

			types.add(type);
		}

		return types;
	}

	/**
	 * 处理附件结果集，添加fileHost
	 * @param typeFiles
	 * @param fileMap
	 */
	private void hanldTypeFiles(List<Map<String, Object>> typeFiles, Map<String, Object> fileMap) {
		if(typeFiles == null) {
			fileMap.put("fileCount", 0);
			fileMap.put("files", null);
			return;
		}
		fileMap.put("fileCount", typeFiles.size());
		List<Map<String, Object>> files = new ArrayList<>();

		Map<String, Object> file = null;
		for (Map<String, Object> typeFile : typeFiles) {
			file = new HashMap<>();
			if(typeFile.get("fileName") == null) {
				continue;
			}
			file.put("fileName", typeFile.get("fileName"));

			if(typeFile.get("filePath") != null) {
				file.put("filePath", typeFile.get("filePath"));
			}

			files.add(file);
		}
		fileMap.put("files", files);
	}

}
